#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <linux/fs.h>
#include <linux/unistd.h>
#include <mntent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include "lab4fs.h"

const char * program_name = "mklab4fs";
struct lab4fs_super_block param;
const char * device_name = NULL;

static void usage(void)
{
	fprintf(stderr, "Usage: %s device\n", program_name);
	exit(1);
}

static int _llseek (unsigned int, unsigned long,
		   unsigned long, long *, unsigned int);

static _syscall5(int,_llseek,unsigned int,fd,unsigned long,offset_high,
		 unsigned long, offset_low,long *,result,
		 unsigned int, origin)

long lab4fs_llseek (unsigned int fd, long offset,
			 unsigned int origin)
{
	unsigned long offset_high;
	unsigned long offset_low;
	long result;
	int retval;
	
	offset_high = ((unsigned long long) offset) >> 32;
	offset_low = ((unsigned long long) offset) & 0xffffffff;
	retval = _llseek (fd, offset_high, offset_low, &result, origin);
	if (retval == -1)
		result = -1;
	return result;
}

static long valid_offset (int fd, long offset)
{
	char ch;
	long temp;
	if ((temp = lab4fs_llseek (fd, offset, 0)) < 0)
		return 0;
	if (read (fd, &ch, 1) < 1) {
		return 0;
	}
	return 1;
}

static int count_blocks (int fd)
{
	long high, low;

	low = 0;
	for (high = 1; valid_offset (fd, high); high *= 2)
		low = high;
	while (low < high - 1)
	{
		const long mid = (low + high) / 2;

		if (valid_offset (fd, mid))
			low = mid;
		else
			high = mid;
	}
	valid_offset (fd, 0);
	return (low + 1) / 1024;
}

static int get_size(const char  *file)
{
	int	fd;
	int	size;

	fd = open(file, O_RDWR);
	if (fd < 0) {
		fprintf(stderr, "Error while trying to determine size of %s: %s",
			file, strerror(errno));
		exit(1);
	}
	if (ioctl(fd, BLKGETSIZE, &size) >= 0) {
		close(fd);
		return size;
	}
	size = count_blocks(fd);
	close(fd);
	return size;
}

static void check_mount(void)
{
	FILE * f;
	struct mntent * mnt;

	if ((f = setmntent (MOUNTED, "r")) == NULL)
		return;
	while ((mnt = getmntent (f)) != NULL)
		if (strcmp (device_name, mnt->mnt_fsname) == 0)
			break;
	endmntent (f);
	if (!mnt)
		return;

	fprintf(stderr, "%s is mounted; will not make a filesystem here!\n",
		device_name);
	exit(1);
}

int main (int argc, char *argv[])
{
	int fd;

	memset(&param, 0, sizeof(struct lab4fs_super_block));
	
	// Get device name
	if (argc && *argv)
		program_name = *argv;
	if (optind == argc)
		usage();
	device_name = argv[optind];
	optind++;
	if (optind < argc)
		usage();
	fprintf(stdout, "Using device: %s\n", device_name);
	
	// Set number of blocks
	param.s_blocks_count = get_size(device_name);
	fprintf(stdout, "Size is %d blocks.\n", param.s_blocks_count);
	
	check_mount();
	
	// Init superblock
	param.s_magic = LAB4FS_MAGIC;
	
	// Write superblock
	fd = open(device_name, O_WRONLY);
	lab4fs_llseek(fd, LAB4FS_BLOCK_SIZE, 0);
	write(fd, &param, 1024);
	
	return 0;
}
